from typing import Union

from fastapi import Depends, FastAPI, HTTPException, Cookie, Header

app = FastAPI()

'''
1.2 demo
'''
async def common_parameters(
    q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
    return {"q": q, "skip": skip, "limit": limit}


@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
    return commons


@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons



'''
2.1 类作为依赖项
'''
class CommonQueryParams:
    def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
        self.q = q
        self.skip = skip
        self.limit = limit

@app.get("/items2/")
async def read_items(commons = Depends(CommonQueryParams)):
    return commons


'''
2.2 嵌套依赖项
'''
def query_extractor(q: Union[str, None] = None):
    return q

def query_or_cookie_extractor(
    q: str = Depends(query_extractor),
    last_query: Union[str, None] = Cookie(default=None),
):
    if not q:
        return last_query
    return q

@app.get("/items3/")
async def read_query(query_or_default: str = Depends(query_or_cookie_extractor)):
    return {"q_or_cookie": query_or_default}


'''
2.3 dependencies 参数
'''
async def verify_token(x_token: str = Header()):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")


async def verify_key(x_key: str = Header()):
    if x_key != "fake-super-secret-key":
        raise HTTPException(status_code=400, detail="X-Key header invalid")
    return x_key


@app.get("/items4/", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items():
    return [{"item": "Foo"}, {"item": "Bar"}]

'''
2.4 全局依赖项
'''
app1 = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])

@app1.get("/items5/")
async def read_items():
    return [{"item": "Portal Gun"}, {"item": "Plumbus"}]



if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)